package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录
     *
     * @param adloginDto
     * @return
     */
    @Override
    public ResponseResult login(AdLoginDto adLoginDto) {
        //1.参数校验
        if (adLoginDto == null && StringUtils.isNotBlank(adLoginDto.getName()) && StringUtils.isNotBlank(adLoginDto.getPassword())){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询数据库
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(adLoginDto.getName() != null,AdUser::getName, adLoginDto.getName()));
        //3.验证用户名和密码
        if (adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String dtoPassword = adLoginDto.getPassword();
        String salt = adUser.getSalt();
        dtoPassword = DigestUtils.md5DigestAsHex((adLoginDto.getPassword() + salt).getBytes());
        if (!adUser.getPassword().equals(dtoPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.生成token返回前端
        Map<String, Object> map = new HashMap<>();
        String token = AppJwtUtil.getToken((long) adUser.getId());
        adUser.setSalt("");
        adUser.setPassword("");
        map.put("token",token);
        map.put("user",adUser);
        return ResponseResult.okResult(map);
    }



}




















